<?php

namespace common\components\api_tool;

use Carbon\Carbon;
use common\components\wtools\tools\ArrayHelper;
use common\Tools;
use GuzzleHttp\Client;

class AdminApi extends ApiTool
{
    public $jwtToken;
    public $token;
    public $key;

    public $proxy = [];

    public function setJwtTokenData($jwtData)
    {
        $jwtDataToken = $jwtData['token'];
        $arr = ArrayHelper::str2arr($jwtDataToken, '.');
        $data1 = base64_decode($arr[1]);
        $data1 = Tools::isJson($data1);
        $this->jwtToken = $jwtDataToken;
        $this->token = $data1['token'];
        $this->key = $jwtData['key'];
        return $this;
    }

    public function post($uri = "", $form_params = [], $isAuth = true)
    {
        $form_params = array_filter($form_params, function ($value) {
            return $value !== null;
        });
        $options = [
            'form_params' => $form_params,
        ];
        return $this->request($uri, $options, 'post', $isAuth);
    }

    public function request($uri = "", $options = [], $method = "post", $isAuth = true)
    {
        $base_uri = $this->getFullUrl($uri);
        $clientOptions = ['base_uri' => $base_uri];
        if (!YII_ENV_PROD) $clientOptions['verify'] = false;
        $client = new Client($clientOptions);
        if ($isAuth) {
            $options['headers'] = [
                'Authorization' => 'Bearer '.$this->jwtToken,
            ];
            $options['form_params'] = $this->generateFormParams($options['form_params'] ?? []);
            if (isset($options['query'])) {
                $options['query'] = $this->generateFormParams($options['query']);
            }
        }
        $resp = $client->request($method, '', $options);
        $resp_cont = $resp->getBody()->getContents();
        $res = Tools::isJson($resp_cont);
        if (!$res || $res['code'] !== 200) {
            throw new \Exception("请求adminApi失败：".$res['message'] ?? '');
        }
        return $res['data'];
    }

    /**
     * @param $user
     * @param array $form_params
     * @return array
     */
    public function generateFormParams($form_params = [])
    {
        $form_params['token'] = $this->token;
        $form_params['timestamp'] = Carbon::now()->timestamp;
        $form_params['nonce'] = $form_params['timestamp'].rand(10000000, 40000000);
        $p = $form_params;
        $p['key'] = $this->key;
        ksort($p);
        unset($p['sign']);
        $p_arr = [];
        foreach ($p as $k => $v) {
            $p_arr[] = $k."=".$v;
        }
        $p_str = ArrayHelper::arr2str($p_arr, '&');
//        Tools::wolog($p_str, 'generateSign');
        $form_params['sign'] = md5($p_str);
        unset($form_params['token']);
        return $form_params;
    }

    /**
     * @param $uri
     * @return string
     */
    public function getFullUrl($uri = "")
    {
        return $this->baseUri.'/adminApi'.$uri;
    }
}
